package com.bruce.common.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PictureUtil {

    public static final long MIN_ZOOM_SIZE = 200L * 1024L;// 200KB

    /**
     * 压缩图片
     *
     * @param picPath  原始图片路径
     * @param zoomPath 压缩后的图片路径
     * @return 压缩后的图片路径
     */
    public static String ZoomPicture(String picPath, String zoomPath) {
        try {
            if (picPath != null && zoomPath != null) {
                File zoom = new File(zoomPath);
                if (!zoom.exists()) {
                    zoom.createNewFile();
                }
                File pic = new File(picPath);
                if (pic.exists()) {
                    int quality = 75;
                    boolean isZoom = true;
                    if (MIN_ZOOM_SIZE >= pic.length()) {// 小于200KB的图片不做压缩处理
                        isZoom = false;
                        quality = 100;
                    }
                    int degree = readPictureDegree(picPath);
                    Bitmap bmp = rotaingBitmap(degree, getZoomBitmap(picPath, isZoom));
                    FileOutputStream fos = new FileOutputStream(zoomPath);
                    bmp.compress(Bitmap.CompressFormat.JPEG, quality, fos);// 把数据写入文件
                    if (!bmp.isRecycled()) {
                        bmp.recycle();
                        System.gc();
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return zoomPath;
    }

//	public static String rotatePicture(String path, String rotatePath){
//		File pic = new File(path);
//		if (pic.exists()) {
//			try {
//				int degree = readPictureDegree(path);
//				Bitmap bmp = rotaingBitmap(degree, MyBitmapFactory.decodeFile(path));
//				FileOutputStream fos = new FileOutputStream(rotatePath);
//				bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
//				if (!bmp.isRecycled()) {
//					bmp.recycle();
//					System.gc();
//				}
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//				return null;
//			}
//		} else {
//			return null;
//		}
//		return rotatePath;
//	}

    /**
     * 旋转图片
     *
     * @param angle 角度
     * @param bmp   要旋转的位图
     * @return 旋转后的位图
     */
    private static Bitmap rotaingBitmap(int angle, Bitmap bmp) {
        if (bmp == null) {
            return null;
        }
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
    }

    /**
     * 计算图片的缩放值
     *
     * @param options   位图参数
     * @param reqWidth  图片宽度
     * @param reqHeight 图片高度
     * @return 缩放值
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
                                             int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param imagesrc
     * @return
     */

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param filePath 路径
     * @param isZoom   是否压缩
     * @return 位图
     */
    private static Bitmap getZoomBitmap(String filePath, boolean isZoom) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        if (isZoom) {
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, 480, 800);
            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
        }
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    private static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exif = new ExifInterface(path);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

}
